# my_flask_app/app.py
from flask import Flask, request, jsonify
from flask_cors import CORS
from itsdangerous import URLSafeTimedSerializer
import uuid

app = Flask(__name__)
app.secret_key = 'your_secret_key'  # 用于加密和解密Token的密钥

# 初始化CORS，允许所有域的跨域请求
CORS(app, supports_credentials=True)

# 存储已登录用户的Token和用户名的映射
logged_in_users = {}

# 初始化URLSafeTimedSerializer实例
serializer = URLSafeTimedSerializer(app.secret_key)

@app.route('/login', methods=['POST'])
def login():
    # 从请求体中获取JSON数据
    data = request.get_json()
    
    # 检查是否提供了必要的数据
    if not data or 'username' not in data or 'password' not in data:
        return jsonify({'error': 'Missing username or password'}), 400
    
    username = data['username']
    password = data['password']
    
    # 验证用户名和密码
    if username == 'admin' and password == '111111':
        # 生成一个唯一的Token
        token = uuid.uuid4().hex
        logged_in_users[token] = username
        
        # 返回Token作为JSON响应
        return jsonify({'token': token})
    else:
        # 返回错误响应
        return jsonify({'error': 'Invalid username or password'}), 401

if __name__ == '__main__':
    app.run(debug=True)